import { type NextRequest, NextResponse } from "next/server"
import { getDb } from "@/lib/db-sqlite"

// 获取单个投票
export async function GET(request: NextRequest, { params }: { params: { id: string } }) {
  try {
    // 正确处理 params
    const { id } = await params
    const db = getDb()

    // 获取投票
    const poll = db
      .prepare(`
      SELECT p.*, 
        json_group_array(
          json_object(
            'id', o.id,
            'poll_id', o.poll_id,
            'text', o.text,
            'votes', o.votes
          )
        ) as options
      FROM polls p
      LEFT JOIN poll_options o ON p.id = o.poll_id
      WHERE p.id = ?
      GROUP BY p.id
    `)
      .get(id)

    if (!poll) {
      return NextResponse.json({ error: "Poll not found" }, { status: 404 })
    }

    // 获取评论
    const comments = db
      .prepare(`
      SELECT * FROM comments
      WHERE poll_id = ?
      ORDER BY created_at DESC
    `)
      .all(id)

    // 处理 JSON 字符串
    try {
      poll.options = JSON.parse(poll.options)
      // 处理空数组的情况
      if (poll.options.length === 1 && poll.options[0].id === null) {
        poll.options = []
      }
    } catch (e) {
      poll.options = []
    }

    // 添加评论到投票对象
    poll.comments = comments

    return NextResponse.json({ poll })
  } catch (error: any) {
    console.error("Error fetching poll:", error)
    return NextResponse.json({ error: error.message || "Failed to fetch poll" }, { status: 500 })
  }
}

// 更新投票状态
export async function PATCH(request: NextRequest, { params }: { params: { id: string } }) {
  try {
    // 正确处理 params
    const { id } = await params
    const { active } = await request.json()

    if (typeof active !== "boolean") {
      return NextResponse.json({ error: "Invalid data" }, { status: 400 })
    }

    const db = getDb()

    // 更新投票状态
    const result = db
      .prepare(`
      UPDATE polls
      SET active = ?
      WHERE id = ?
    `)
      .run(active ? 1 : 0, id)

    if (result.changes === 0) {
      return NextResponse.json({ error: "Poll not found" }, { status: 404 })
    }

    return NextResponse.json({ success: true })
  } catch (error: any) {
    console.error("Error updating poll:", error)
    return NextResponse.json({ error: error.message || "Failed to update poll" }, { status: 500 })
  }
}

// 删除投票
export async function DELETE(request: NextRequest, { params }: { params: { id: string } }) {
  try {
    // 正确处理 params
    const { id } = await params
    const db = getDb()

    // 删除投票
    const result = db
      .prepare(`
      DELETE FROM polls
      WHERE id = ?
    `)
      .run(id)

    if (result.changes === 0) {
      return NextResponse.json({ error: "Poll not found" }, { status: 404 })
    }

    return NextResponse.json({ success: true })
  } catch (error: any) {
    console.error("Error deleting poll:", error)
    return NextResponse.json({ error: error.message || "Failed to delete poll" }, { status: 500 })
  }
}
